/**
 * Copyright 2014 lerry
 * 
 * All right reserved.
 * 
 * Dec 8, 2014
 */
package com.bac.bacplatform;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.Inflater;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.bac.utils.Config;
import com.bac.utils.Storage;
import com.bac.utils.Util;
import com.baidu.platform.comapi.map.t;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

/**
 * @author lerry
 * 
 */
public class FragmentHome extends BaseFragment implements OnClickListener{
	private PopupWindow mPopupWindow;
	
	private ViewPager mViewPager;
	
	private PagerAdapter mAdapter;

	// 广告栏图片
	private ArrayList<String> mImages;

	// 广告栏小点
	private List<View> mDotsList;
	private LinearLayout mDotsGroupLayout;

	private AtomicInteger atomicInteger = new AtomicInteger(0);
	
	private ScheduledExecutorService scheduledExecutorService;

	private ArrayList<HashMap<String, String>> mAdList;
	DisplayImageOptions options;
	
	
	TextView mYieldTextView,mSingleYieldTextView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_main, null);
		mSingleYieldTextView = (TextView) view.findViewById(R.id.preferential_text2);
		mYieldTextView = (TextView)view.findViewById(R.id.max_preferential_text2);
		initYieldView();
		LinearLayout lay_more = (LinearLayout) view.findViewById(R.id.lay_more);
		lay_more.setOnClickListener(this);
		mDotsGroupLayout = (LinearLayout) view.findViewById(R.id.viewGroup);
		  
		options = new DisplayImageOptions.Builder()  
		 .showImageOnLoading(R.drawable.banner_default) //设置图片在下载期间显示的图片  
		 .showImageForEmptyUri(R.drawable.banner_default)//设置图片Uri为空或是错误的时候显示的图片  
		.showImageOnFail(R.drawable.banner_default)  //设置图片加载/解码过程中错误时候显示的图片
		.cacheInMemory(true)//设置下载的图片是否缓存在内存中  
		.cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中  
		.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示  
		.bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//  
		.build();
		initViewPager(view);
		setOnclickListener(view);
		return view; 
	}
	
	/**
	 * 初始化利率
	 */
	private void initYieldView(){
		String singleYieldString = Storage.getString(getActivity().getApplicationContext(), "SingleYield");
		singleYieldString = singleYieldString.equals("")?"0.00":singleYieldString;
		String yieldString =  Storage.getString(getActivity().getApplicationContext(), "Yield");
		yieldString = yieldString.equals("")?"0.00":yieldString;
		mSingleYieldTextView.setText(""+(int)(Double.parseDouble(singleYieldString)*100));
		mYieldTextView.setText(""+(int)(Double.parseDouble(yieldString)*100));
		
	}
	
	public void setOnclickListener(View view){
		View include = (View)view.findViewById(R.id.include_menus);
//		LinearLayout lay_recharge = (LinearLayout)include.findViewById(R.id.btn7);
//		lay_recharge.setOnClickListener(this);
//		LinearLayout lay_gastreasure = (LinearLayout)include.findViewById(R.id.btn5);
//		lay_gastreasure.setOnClickListener(this);
//		LinearLayout lay_preferentialgas = (LinearLayout)include.findViewById(R.id.btn6);
//		lay_preferentialgas.setOnClickListener(this);
//		include.findViewById(R.id.btn1).setOnClickListener(this);
//		include.findViewById(R.id.btn2).setOnClickListener(this);
//		include.findViewById(R.id.btn3).setOnClickListener(this);
//		include.findViewById(R.id.btn4).setOnClickListener(this);
		view.findViewById(R.id.img_map_nav).setOnClickListener(this);
		
		include.findViewById(R.id.menu_gas_button).setOnClickListener(this);
		include.findViewById(R.id.buddy_left_top).setOnClickListener(this);
		include.findViewById(R.id.buddy_left_center).setOnClickListener(this);
		include.findViewById(R.id.buddy_left_down).setOnClickListener(this);
		
		
	}
	
	@Override
	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 2, 5,
				TimeUnit.SECONDS);
		System.gc();
		super.onStart();
	}
	
	@Override
	public void onStop() {
		// 当Activity不可见的时候停止切换
		scheduledExecutorService.shutdown();
		super.onStop();
	}
	
	/**
	 * 广告图片切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (mViewPager) {
				atomicOption();
				viewHandler.sendEmptyMessage(atomicInteger.get());
			}
		}

	}
	
	private void atomicOption() {
		atomicInteger.incrementAndGet();
		if (atomicInteger.get() > mImages.size() - 1) {
			atomicInteger.getAndAdd(- mImages.size());
		}
	}

	private void initViewPager(View view) {
		// 从布局文件中获取ViewPager父容器
		LinearLayout pagerLayout = (LinearLayout) view
				.findViewById(R.id.view_pager_content);
		// 创建ViewPager
		mViewPager = new ViewPager(getActivity());

		// 自适应高度
		int picHeight = Util.getAdjustImageHeigh(getResources(),R.drawable.banner_default,getActivity());

		// 根据图片高度设置广告栏高度
		mViewPager.setLayoutParams(new LayoutParams(Util.getWidth(getActivity()),
				picHeight));

		// 将ViewPager容器设置到布局文件父容器中
		pagerLayout.addView(mViewPager);

		initPageAdapter();
		mViewPager.setOnPageChangeListener(new AdPageChangeListener());
		
		initAds();
		getRechargeConfig();
	}

	private void getRechargeConfig(){

		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				
				
				Log.i("yield----", response);
				
				Type type = new TypeToken<HashMap<String, String>>(){
				}.getType();
				Gson gson = new Gson();
				HashMap<String, String> result = gson.fromJson(response, type);
				if (result != null && result.containsKey("Yield") && result.containsKey("SingleYield")) {
					String yieldString = result.get("Yield");
					String singleYieldString = result.get("SingleYield");
					yieldString = yieldString.equals(" ")?"0.00":yieldString;
					singleYieldString = singleYieldString.equals(" ")?"0.00":singleYieldString;
					
					mSingleYieldTextView.setText(""+(int)(Double.parseDouble(singleYieldString)*100));
					mYieldTextView.setText(""+(int)(Double.parseDouble(yieldString)*100));
					
					Storage.saveString(getActivity().getApplicationContext(), "Yield", yieldString);
					Storage.saveString(getActivity().getApplicationContext(), "SingleYield", singleYieldString);
					
				}
			}
		};
		
		
		String path = Config.URL_RECHARGE_CONFIG;
		Util.httpRequestToGet(path, sListener, this);
	
	}
	
	private void initAds(){

		// 如果没有网络，就加载本地图片
		ErrorListener errorListener = new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError arg0) {
				Log.i("get ads error", "no network");
				mImages.add("drawable://"+R.drawable.banner_default);
				mAdapter.notifyDataSetChanged();
			}
		};
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.i("home ads", response);
				// 解析广告栏数组
				Type listType = new TypeToken<ArrayList<HashMap<String, String>>>() {
				}.getType();
				Gson gson = new Gson();
				mAdList = gson.fromJson(response, listType);
				if (mAdList.size() == 0) {
					mImages.add("drawable://"+R.drawable.banner_default);
					mAdapter.notifyDataSetChanged();
				}else{
					for (Map<String, String> ad : mAdList) {
						mImages.add(ad.get("image"));
					}
				}
				
				initCirclePoint();
				mAdapter.notifyDataSetChanged();
			}
		};
		
		String path = Config.URL_HOME_ADS;
		Util.httpRequestToGet(path, sL, errorListener);
	
	}
	

	/**
	 * 切换当前显示的图片
	 */
	@SuppressLint("HandlerLeak")
	private final Handler viewHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			mViewPager.setCurrentItem(msg.what);
			super.handleMessage(msg);
		}

	};

	private void initPageAdapter() {
		mImages = new ArrayList<String>();
		mAdapter = new BannerAdapter();
		mViewPager.setAdapter(mAdapter);
	}

	private void initCirclePoint() {

		mDotsList = new ArrayList<View>();

		try {
			mDotsGroupLayout.removeAllViews();
		} catch (Exception ex) {

		}

		LinearLayout.LayoutParams pl = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		pl.setMargins(5, 0, 5, 0);
		// 广告栏的小圆点图标
		for (int i = 0; i < mImages.size(); i++) {
			LinearLayout lay = new LinearLayout(getActivity());
			lay.setLayoutParams(pl);
			// 初始值, 默认第0个选中
			if (i == 0) {
				lay.setBackgroundResource(R.drawable.home_banner_current_dot);
			} else {
				lay.setBackgroundResource(R.drawable.home_banner_next_dot);
			}

			// 将小圆点放入到布局中
			mDotsGroupLayout.addView(lay);
			mDotsList.add(lay);
		}
	}

	/**
	 * ViewPager 页面改变监听器
	 */
	private final class AdPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * 页面滚动状态发生改变的时候触发
		 */
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		/**
		 * 页面滚动的时候触发
		 */
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		/**
		 * 页面选中的时候触发
		 */
		@Override
		public void onPageSelected(int arg0) {
			// 获取当前显示的页面是哪个页面
			atomicInteger.getAndSet(arg0);
			mDotsList.get(oldPosition).setBackgroundResource(
					R.drawable.home_banner_next_dot);
			mDotsList.get(arg0).setBackgroundResource(
					R.drawable.home_banner_current_dot);
			oldPosition = arg0;
		}
	}

	private final class BannerAdapter extends PagerAdapter {

		/**
		 * 从ViewPager中删除集合中对应索引的View对象
		 */
		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		/**
		 * 获取ViewPager的个数
		 */
		@Override
		public int getCount() {
			return mImages.size();
		}

		/**
		 * 从View集合中获取对应索引的元素, 并添加到ViewPager中
		 */
		@Override
		public Object instantiateItem(View container, final int position) {
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			
			ImageLoader imageLoader = ImageLoader.getInstance();
			
			ImageView imageView = new ImageView(getActivity());
			imageView.setLayoutParams(params);
			imageView.setScaleType(ScaleType.FIT_XY);
			imageView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// TODO 添加点击事件
					if (mAdList != null && mAdList.size() > position) {
						// 广告详情
						Intent intentToAgree = new Intent(getActivity(),
								BacAgreementWebActivity.class);
						intentToAgree.putExtra("urltype", "ads_detail");
						intentToAgree.putExtra("ads_id", ""+mAdList.get(position).get("id"));
						startActivityIn(intentToAgree);
						Log.i("ads -----id",
								"" + mAdList.get(position).get("id"));
					}else{
						Intent intentToAgree = new Intent(getActivity(),
								BacAgreementWebActivity.class);
						intentToAgree.putExtra("urltype", "ads_local");
						intentToAgree.putExtra("ads_url", "http://wechat.bac365.com/card/into");
						startActivityIn(intentToAgree);
					}
					
				}
			});
			imageLoader.displayImage(mImages.get(position), imageView, options , new SimpleImageLoadingListener(){

				@Override
				public void onLoadingStarted(String imageUri, View view) {
					super.onLoadingStarted(imageUri, view);
					Log.i("image loading start", "----start");
				}

				@Override
				public void onLoadingFailed(String imageUri, View view,
						FailReason failReason) {
					super.onLoadingFailed(imageUri, view, failReason);
					Log.i("image loading failed", "----failed");
				}

				@Override
				public void onLoadingComplete(String imageUri, View view,
						Bitmap loadedImage) {
					super.onLoadingComplete(imageUri, view, loadedImage);
					Log.i("image loading complete", "----complete");
				}
				
				
			});
			try {
				((ViewPager) container).addView(imageView);
			} catch (Exception ex) {

			}
			return imageView;
		}

		/**
		 * 是否将显示的ViewPager页面与instantiateItem返回的对象进行关联 这个方法是必须实现的
		 */
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn1:
			Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
			break;
		case R.id.btn2:
			Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
			break;
		case R.id.btn3:
			Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
			break;
		case R.id.btn4:
			Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
			break;
		case R.id.btn7:
//			Intent intentToRecharge = new Intent(getActivity(), RechargeActivity.class);
//			startActivity(intentToRecharge);
			break;
		case R.id.btn5:
			Intent intentToOilWallet = new Intent(getActivity(),OilWalletActivity.class);
			startActivity(intentToOilWallet);
			break;
		case R.id.btn6:
			Intent intentToBuyCoupon = new Intent(getActivity(),BuyCouponActivity.class);
			startActivity(intentToBuyCoupon);
			break;
		case R.id.img_map_nav:
			Intent intentToFuelingGas = new Intent(getActivity(), FuelingGasActivity.class);
			startActivity(intentToFuelingGas);
			break;
			//新页面
		case R.id.menu_gas_button:
			Intent intent = new Intent(getActivity(), KeyToOilActivity.class);
			startActivity(intent);
			break;
		case R.id.buddy_left_top:
//			Intent intentToFindPick = new Intent(getActivity(), FindPickActivity.class);
//			startActivity(intentToFindPick);
			break;
		case R.id.buddy_left_center:
//			Intent intentToKey = new Intent(getActivity(), KeyToOilActivity.class);
//			startActivity(intentToKey);
			break;
		case R.id.buddy_left_down:
//			Intent intentToCash = new Intent(getActivity(), CashToOilActivity.class);
//			startActivity(intentToCash);
			break;
		case R.id.lay_more:
//			Toast.makeText(getActivity(),"more",Toast.LENGTH_SHORT).show();
			if (mPopupWindow != null && mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
 				return;
			} else {
				initmPopupWindowView();
				mPopupWindow.showAsDropDown(v, -70, 0);
				
			}
		default:
			break;
		}
	}

	private void initmPopupWindowView() {
		View customView = getLayoutInflater(getArguments()).inflate(R.layout.more, null);
		mPopupWindow = new PopupWindow(customView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setFocusable(true);
		customView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mPopupWindow != null && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
					mPopupWindow = null;
				}
				return false;
			}
		});
		//拨打客服电话
		RelativeLayout call_us = (RelativeLayout) customView.findViewById(R.id.call_us);
		call_us.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//拨打电话
				String number = "4001106262";
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:"+number));
				startActivity(intent);
				mPopupWindow.dismiss();
			}
		});
		//查看关于我们
		RelativeLayout about_us = (RelativeLayout) customView.findViewById(R.id.about_us);
		about_us.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 查看关于我们协议
				Intent intentToAgree = new Intent(getActivity(),
						BacAgreementWebActivity.class);
				intentToAgree.putExtra("urltype", "about_us");
				startActivityIn(intentToAgree);
				mPopupWindow.dismiss();
			}
		});
	}

}

